package com.wing.order.controller.app;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.HttpHelper;
import com.wing.common.utils.JsonResult;
import com.wing.config.BaseDataInit;
import com.wing.order.model.entity.*;
import com.wing.order.model.response.OrderDeliveryDetailVO;
import com.wing.order.model.response.ScanDeliveryVo;
import com.wing.order.model.response.ScanPickUpVo;
import com.wing.order.service.*;
import com.wing.platform.feign.PlatformClient;
import com.wing.warehouse.model.entity.Warehouse;
import com.wing.warehouse.service.WarehouseService;
import com.wing.web.utils.JwtUtils;
import com.wing.web.utils.LocaleMessage;
import com.wing.common.utils.PageResult;
import com.wing.order.model.response.OrderDeliveryVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.wing.order.model.request.OrderDeliveryForm;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @author
 */
@Slf4j
@Validated
@Api(value = "App-配送管理", tags = "配送管理")
@RestController("appOrderDeliveryController")
@RequestMapping("order/app/orderDelivery")
public class OrderDeliveryController {

    @Autowired
    private OrderDeliveryService orderDeliveryService;
    @Autowired
    private LocaleMessage localeMessage;

    @Autowired
    private OrderDeliveryDetailService orderDeliveryDetailService;

    @Autowired
    private OrderDeliverySingnumService orderDeliverySingnumService;

    @Autowired
    private WarehouseService warehouseService;

    @Autowired
    private OrderDistributionLabelService orderDistributionLabelService;

    @Autowired
    private InventoryInoutJobService jobService;

    @Autowired
    private PlatformClient platformClient;
    @Value("${platform.gatewayUrl}")
    private String gatewayUrl;



    @GetMapping("/list")
    public PageResult<OrderDeliveryVO> list(
            @RequestParam(name = "page", defaultValue = "1", required = false) Integer page
            , @RequestParam(name = "limit", defaultValue = "10", required = false) Integer limit
            , @RequestParam(name = "sort", defaultValue = "create_time", required = false) String sort
            , @RequestParam(name = "order", defaultValue = "desc", required = false) String order
    ) {
        Page<OrderDeliveryVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }

        Page<OrderDeliveryVO> list = orderDeliveryService.pageList4app(pg, params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @GetMapping("/{id}")
    public JsonResult detail(@PathVariable("id") Long orderDeliveryId) {
        OrderDeliveryVO orderDeliveryVO = orderDeliveryService.get4appById(orderDeliveryId);
        if (orderDeliveryVO == null) {
            return JsonResult.fail(localeMessage.getMessage("common.fail"));
        }
        return JsonResult.success(localeMessage.getMessage("common.success"), orderDeliveryVO);
    }

    @PostMapping()
    public JsonResult add(@Validated OrderDeliveryForm orderDeliveryForm) {
        if (orderDeliveryService.add(orderDeliveryForm) > 0) {
            return JsonResult.success(localeMessage.getMessage("common.success"));
        }
        return JsonResult.fail(localeMessage.getMessage("common.fail"));
    }


    /**
     * 查看待签收  调用平台端数据获取
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "待签收", notes = "查询")
    @GetMapping("/getSignInfo")
    public PageResult<OrderDeliveryVO> getSign(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "asc") String order

    ) throws Exception {

        //访问路径
        String reqUri = gatewayUrl + "platformCab/order/app/orderDelivery/getSignInfo";

        //转换成字符串
        String newPage = Integer.toString(page);
        String newLimit = Integer.toString(limit);

        String reqNewUri = reqUri.concat("?page=").concat(newPage).concat("&limit=").concat(newLimit)
                .concat("&sort=").concat(sort).concat("&order=").concat(order);


        if (JwtUtils.getEnterpriseId()!=null) {
            reqNewUri = reqUri.concat("?page=").concat(newPage).concat("&limit=").concat(newLimit)
                    .concat("&sort=").concat(sort).concat("&order=").concat(order)
                    .concat("&enterpriseId=").concat(String.valueOf(JwtUtils.getEnterpriseId()));
        }
        //发送请求
        String jsonInfo = HttpHelper.httpGet(reqNewUri);
        //将平台端的json转换成List  因里面有别的数据，而我们需要的对象集合存在data，取键拿出
        JSONObject obj = JSONObject.parseObject(jsonInfo);
        JSONArray arr = obj.getJSONArray("data");
        String js = JSON.toJSONString(arr, SerializerFeature.WriteClassName);
        //转换成集合
        List<OrderDeliveryVO> orderDeliveryList = JSON.parseObject(js, List.class);

        return new PageResult(orderDeliveryList, obj.getInteger("count"));
    }


    /**
     * 根据签收单号 查询同一批次的产品
     * 订单信息 调用平台端
     *
     * @param deliveryOrderCode 配送单编号
     * @return
     */
    @GetMapping("/orderInfo")
    public JsonResult<List<OrderDeliveryDetailVO>> orderInfo(@RequestParam String deliveryOrderCode) throws Exception {

        //访问路径
        String reqUri = gatewayUrl + "platformCab/order/app/orderDelivery/orderInfo";
        final String newUri = reqUri.concat("?deliveryOrderCode=").concat(deliveryOrderCode);
        //请求
        String jsonInfo = HttpHelper.httpGet(newUri);
        JSONObject obj = JSONObject.parseObject(jsonInfo);
        //拿到数据
        JSONArray array = obj.getJSONArray("data");

        String js = JSON.toJSONString(array, SerializerFeature.WriteClassName);

        log.info(array + "");

        //转换成集合
        List<OrderDeliveryDetailVO> list = JSON.parseObject(js, List.class);

        return JsonResult.success(list);
    }





    /**
     * 添加签收信息 带出产品信息
     *
     * @param deliveryOrderCode 签收单
     * @param packLabelCode     扫描条码
     * @param detailId 明细id
     */
    @GetMapping("/addReceipt")
    public JsonResult<OrderDeliveryDetailVO> addReceipt(@RequestParam("packLabelCode") String packLabelCode,
                                                  @RequestParam("deliveryOrderCode") String deliveryOrderCode,
                                                  @RequestParam(value = "detailId",required = false)Integer detailId) throws Exception {
        //调用平台端
        //发送请求
        Object jsonInfo = platformClient.addReceipt(packLabelCode,deliveryOrderCode,detailId);
        if (jsonInfo == null) {
            return JsonResult.fail("该包装条码不是当前订单,或已签收");
        }
        return JsonResult.success(jsonInfo);
    }

    /**
     * 商品列表 top
     */
    @GetMapping("/getDeliverInfo")
    public JsonResult<OrderDeliveryVO> getDeliverInfo(@RequestParam String deliveryOrderCode){
        com.wing.platform.order.model.response.OrderDeliveryVO vo = platformClient.getDeliverInfo(deliveryOrderCode);
        return JsonResult.success(vo);
    }




    /**
     * 扫码签收
     * @param packLabelCode     包装码
     * @param realReceive       实收数量
     * @param deliveryOrderCode 签收单号
     * @param  quantityReceive 应收数
     */
    @GetMapping("/scanSign")
    public JsonResult scanSign(@RequestParam("packLabelCode") String packLabelCode
                                ,@RequestParam("realReceive")Integer realReceive
                                ,@RequestParam("deliveryOrderCode")String deliveryOrderCode
                                ,@RequestParam(value = "remark",required = false)String remark
                                ,@RequestParam("abnormalNum")Integer abnormalNum
                                ,@RequestParam("detailId") Integer detailId
                                ,@RequestParam("quantityReceive")Integer quantityReceive
    ) throws Exception {
        //计算异常数量
        Integer exNum =quantityReceive-realReceive;
        //调用平台端
        JSONObject jsonInfo = platformClient.scanSign(packLabelCode, realReceive, deliveryOrderCode,remark,exNum,detailId);
        LinkedHashMap<String, Object> linkedHashMap = (LinkedHashMap<String, Object>) jsonInfo.get("data");
        if (linkedHashMap.size() == 0) {
            return JsonResult.fail("签收数量大于应收数量,或已被扫描过");
        }
        JSONObject object = JSONObject.parseObject(String.valueOf(jsonInfo));
        JSONObject deliveryDetailVO = object.getJSONObject("data");
        return JsonResult.success(deliveryDetailVO);
    }

    /**
     * 查询已扫描信息
     */
    @GetMapping("/getScanInfo")
    public JsonResult<ScanDeliveryVo> getScanInfo(@RequestParam("deliveryOrderCode") String deliveryOrderCode) {
        JSONObject obj = platformClient.getScanInfo(deliveryOrderCode);
        JSONArray array = obj.getJSONArray("data");
        String js = JSON.toJSONString(array, SerializerFeature.WriteClassName);
        List<OrderDeliveryVO> list = JSON.parseObject(js, List.class);
        return JsonResult.success(list);
    }

    /**
     * 选择仓库
     */
    @GetMapping("/getWareHouse")
    public JsonResult<Warehouse> getWareHouse() {
        List<Warehouse> warehouseList = warehouseService.list();
        return JsonResult.success(warehouseList);
    }



    /**
     * 确定提交  同步平台端数据
     */
    @PostMapping("/signSubmit")
    public JsonResult signSubmit(@RequestBody List<ScanDeliveryVo> list) {

        //同步平台数据
        try{
            orderDeliveryService.signSubmit(list);
            return JsonResult.success("提交成功");
        }catch (Exception e){
            log.error("sign submit fail",e);
            return JsonResult.fail(e.getMessage());

        }
    }

    /**
     * 签收明细
     * @param skuCode           产品编号
     * @param deliveryOrderCode 批号
     */
    @GetMapping("/signProduct")
    public JsonResult<OrderDeliveryDetailVO> signProduct(@RequestParam("skuCode") String skuCode, @RequestParam("deliveryOrderCode") String deliveryOrderCode) {

        List<OrderDeliveryVO> orderDeliveryVO = orderDeliveryService.signProduct(skuCode, deliveryOrderCode);
        return JsonResult.success(orderDeliveryVO);
    }
    /**
     * 已签收列表
     */
    @GetMapping("/infoSignList")
    public PageResult<OrderDeliveryVO> infoSignList(
            @RequestParam(name = "page", defaultValue = "1", required = false) Integer page
            , @RequestParam(name = "limit", defaultValue = "10", required = false) Integer limit
            , @RequestParam(name = "sort", defaultValue = "create_time", required = false) String sort
            , @RequestParam(name = "order", defaultValue = "desc", required = false) String order) {

        Page<OrderDeliveryVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }

        Page<OrderDeliveryVO> list = orderDeliveryService.infoSignList(pg, params);

        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    /**
     * 已签收详情列表
     */
    @GetMapping("/infoSign")
    public JsonResult<OrderDeliveryVO> infoSign(@RequestParam("deliveryOrderCode") String deliveryOrderCode) {

        List<OrderDeliveryVO> vo = orderDeliveryService.infoSign(deliveryOrderCode);
        return JsonResult.success(vo);
    }


    /**
     * 入库
     *
     * @param deliveryOrderCode 配送单编号
     * @param warhouseId        仓库id
     */
    @GetMapping("/getWarehousing")
    public JsonResult getWarehousing(@RequestParam String deliveryOrderCode, @RequestParam Integer warhouseId) {
        List<OrderDeliveryVO> deliveryVOList = orderDeliveryService.infoSign(deliveryOrderCode);
        jobService.saveInventoryInoutJob(deliveryVOList, warhouseId);
        int temp = 0;

        for (int i = 0; i < deliveryVOList.size(); i++) {
            OrderDeliveryDetail detail = orderDeliveryDetailService.getById(deliveryVOList.get(i).getId());
            if (detail.getStatus().equals(OrderDeliveryDetail.Status.InStock)) {
                temp++;
            }
        }
        if (temp == deliveryVOList.size()) {
            //修改配送表的仓库
            OrderDelivery orderDelivery = new OrderDelivery();
//            orderDelivery.setId(Long.valueOf(deliveryVOList.get(0).getDeliveryId()));
            orderDelivery.setWarhouseId(Long.valueOf(warhouseId));
            orderDelivery.setStatus(OrderDelivery.Status.inStorage);
            orderDeliveryService.updateById(orderDelivery);
        }
        return JsonResult.success("已入库");
    }


    /**
     * 查询领货列表
     * Pickup List
     */
    @GetMapping("/pickupList")
    public PageResult<OrderDeliveryVO> pickupList(
            @RequestParam(name = "page", defaultValue = "1", required = false) Integer page
            , @RequestParam(name = "limit", defaultValue = "10", required = false) Integer limit
            , @RequestParam(name = "sort", defaultValue = "create_time", required = false) String sort
            , @RequestParam(name = "order", defaultValue = "desc", required = false) String order) {

        //查询状态为已入库的

        Page<OrderDeliveryVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        Page<OrderDeliveryVO> list = orderDeliveryService.pickupList(pg, params);

        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    /**
     * 领货详情列表
     */
    @GetMapping("/pickupDetail")
    public JsonResult<OrderDeliveryDetailVO> pickupDetail(@RequestParam("deliveryOrderCode") String deliveryOrderCode) {

        List<OrderDeliveryDetailVO> vo = orderDeliveryService.pickupDetail(deliveryOrderCode);
        return JsonResult.success(vo);
    }


    /**
     * 领货扫码带出产品信息
     *
     * @param deliveryOrderCode 领货订单编号(签收单编号)
     * @param packLabelCode     包装条码
     */
    @GetMapping("/scanPickupInfo")
    public JsonResult<ScanDeliveryVo> scanPickupInfo(@RequestParam("packLabelCode") String packLabelCode, @RequestParam("deliveryOrderCode") String deliveryOrderCode) {
        ScanDeliveryVo pickupInfo = orderDeliveryDetailService.scanPickupInfo(packLabelCode, deliveryOrderCode);

        return JsonResult.success(pickupInfo);
    }


    /**
     * 扫码 領貨  扫一个出一个库
     * @param packLabelCode     包装条码
     * @param realReceive       签收数量
     * @param deliveryOrderCode 领货订单编号(签收单编号)
     */
    @GetMapping("/getPickUp")
    public JsonResult getPickUp(@RequestParam("packLabelCode") String packLabelCode,
                                @RequestParam("realReceive") Integer realReceive,
                                @RequestParam("deliveryOrderCode") String deliveryOrderCode,
                                @RequestParam("remark") String remark) {

        ScanDeliveryVo scanPickupInfo = orderDeliveryDetailService.scanPickupInfo(packLabelCode, deliveryOrderCode);
        try {
            jobService.outOfStock(scanPickupInfo, realReceive, remark);
            int temp = 0;
            List<OrderDeliveryDetailVO> vo = orderDeliveryService.pickupDetail(deliveryOrderCode);
            //判断当前产品是否被扫描
            for (int i = 0; i < vo.size(); i++) {
                if (vo.get(i).getIsScan()) {
                    temp++;
                }
            }
            if (temp == vo.size()) {
                //配送表
                OrderDelivery orderDelivery = new OrderDelivery();
                orderDelivery.setId(Long.valueOf(scanPickupInfo.getDeliveryId()));
                orderDelivery.setStatus(OrderDelivery.Status.receive);
                orderDeliveryService.updateById(orderDelivery);
            }
        } catch (Exception e) {
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
        return JsonResult.success("领货完成");
    }


    /**
     * 已领货信息
     */
    @GetMapping("/getPickUpFinsh")
    public JsonResult<ScanPickUpVo> getPickUpFinsh(@RequestParam("deliveryOrderCode") String deliveryOrderCode) {
        List<ScanPickUpVo> pickUpFinsh = orderDistributionLabelService.getPickUpFinsh(deliveryOrderCode);
        return JsonResult.success(pickUpFinsh);
    }




    /**
     * 签收明细 SN码明细
     * @param skuCode 产品编号
     */
    @GetMapping("/signDetail")
    public JsonResult<OrderDeliveryDetail> signDetail(@RequestParam("skuCode") String skuCode) {
        List<OrderDeliveryDetailVO> list = orderDeliveryDetailService.signDetail(skuCode);
        return JsonResult.success();
    }



}
